<template>
  <div class="route-observer-demo">
    <el-page-header @back="$router.go(-1)" content="路由观察者模式演示" />
    
    <div class="demo-content">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-card title="观察者模式演示">
            <template #header>
              <div class="card-header">
                <span>观察者模式演示</span>
                <el-button @click="showMonitor = !showMonitor" type="primary" size="small">
                  {{ showMonitor ? '隐藏监控' : '显示监控' }}
                </el-button>
              </div>
            </template>

            <div class="demo-section">
              <h3>1. 基础路由观察者</h3>
              <p>这个页面已经自动注册了基础的路由观察者，包括：</p>
              <ul>
                <li>页面标题观察者 - 自动更新页面标题</li>
                <li>面包屑观察者 - 更新导航面包屑</li>
                <li>用户状态观察者 - 检查用户认证状态</li>
                <li>缓存观察者 - 管理页面相关缓存</li>
              </ul>

              <el-divider />

              <h3>2. 自定义观察者</h3>
              <el-space direction="vertical" style="width: 100%">
                <el-button @click="addCustomObserver" type="success">
                  添加自定义观察者
                </el-button>
                <el-button @click="removeCustomObserver" type="danger" :disabled="!customObserver">
                  移除自定义观察者
                </el-button>
                <el-button @click="triggerManualUpdate" type="warning">
                  手动触发更新
                </el-button>
              </el-space>

              <div v-if="customObserverLog.length > 0" class="observer-log">
                <h4>自定义观察者日志：</h4>
                <el-timeline>
                  <el-timeline-item
                    v-for="(log, index) in customObserverLog"
                    :key="index"
                    :timestamp="formatTime(log.timestamp)"
                  >
                    {{ log.message }}
                  </el-timeline-item>
                </el-timeline>
              </div>

              <el-divider />

              <h3>3. 导航测试</h3>
              <p>点击下面的按钮来测试路由观察者：</p>
              <el-space wrap>
                <el-button @click="$router.push('/home')">跳转到首页</el-button>
                <el-button @click="$router.push('/knowledge')">跳转到知识库</el-button>
                <el-button @click="$router.push('/appointment')">跳转到预约</el-button>
                <el-button @click="$router.push('/about')">跳转到关于</el-button>
              </el-space>

              <el-divider />

              <h3>4. 页面状态信息</h3>
              <el-descriptions title="当前页面状态" :column="2" border>
                <el-descriptions-item label="当前路径">
                  {{ currentRoute?.path }}
                </el-descriptions-item>
                <el-descriptions-item label="页面名称">
                  {{ currentRoute?.name }}
                </el-descriptions-item>
                <el-descriptions-item label="观察者数量">
                  {{ observerCount }}
                </el-descriptions-item>
                <el-descriptions-item label="导航历史数量">
                  {{ routeHistory.length }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card title="实时状态">
            <div class="status-panel">
              <el-alert 
                title="观察者状态" 
                :description="`当前页面有 ${observerCount} 个活跃观察者`"
                type="info"
                :closable="false"
              />

              <div class="breadcrumb-display">
                <h4>当前面包屑：</h4>
                <el-breadcrumb separator="/">
                  <el-breadcrumb-item 
                    v-for="(item, index) in breadcrumbs" 
                    :key="index"
                  >
                    {{ item.name }}
                  </el-breadcrumb-item>
                </el-breadcrumb>
              </div>

              <div class="performance-display">
                <h4>性能信息：</h4>
                <el-statistic 
                  title="平均加载时间" 
                  :value="performanceData.averageLoadTime || 0" 
                  suffix="ms"
                />
              </div>

              <div class="recent-routes">
                <h4>最近访问：</h4>
                <el-tag 
                  v-for="(route, index) in recentRoutes" 
                  :key="index"
                  size="small"
                  style="margin: 2px"
                >
                  {{ route.name || route.path }}
                </el-tag>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 监控面板 -->
      <div v-if="showMonitor" class="monitor-panel">
        <RouteObserverMonitor />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouteStore } from '@/stores/route'
import { 
  useRouteObserver, 
  usePageRouteObserver, 
  useRoutePerformance 
} from '@/composables/useRouteObserver'
import RouteObserverMonitor from '@/components/RouteObserverMonitor.vue'

const routeStore = useRouteStore()

// 路由观察者相关
const { 
  setupDefaultObservers, 
  addCustomObserver: addRouteObserver, 
  removeObserver,
  triggerUpdate 
} = useRouteObserver()

// 性能监控
const { 
  performanceData, 
  setupPerformanceMonitoring 
} = useRoutePerformance()

// 页面级路由观察者
usePageRouteObserver('RouteObserverDemo', {
  onEnter: (routeInfo) => {
    console.log('进入路由观察者演示页面:', routeInfo)
    addLog('页面观察者：进入演示页面')
  },
  onLeave: (from, to) => {
    console.log('离开路由观察者演示页面:', from, '->', to)
    addLog('页面观察者：离开演示页面')
  },
  onUpdate: (routeInfo) => {
    console.log('路由观察者演示页面更新:', routeInfo)
    addLog(`页面观察者：路由更新 ${routeInfo.path}`)
  }
})

// 响应式数据
const showMonitor = ref(false)
const customObserver = ref(null)
const customObserverLog = ref([])
const observerCount = ref(0)

// 计算属性
const currentRoute = computed(() => routeStore.currentRoute)
const breadcrumbs = computed(() => routeStore.breadcrumbs)
const routeHistory = computed(() => routeStore.routeHistory)

const recentRoutes = computed(() => {
  return routeHistory.value.slice(-5).reverse()
})

// 方法
const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleString('zh-CN')
}

const addLog = (message) => {
  customObserverLog.value.unshift({
    message,
    timestamp: Date.now()
  })
  
  // 限制日志数量
  if (customObserverLog.value.length > 10) {
    customObserverLog.value = customObserverLog.value.slice(0, 10)
  }
}

const addCustomObserver = () => {
  if (customObserver.value) {
    ElMessage.warning('自定义观察者已存在')
    return
  }

  customObserver.value = addRouteObserver((routeInfo) => {
    addLog(`自定义观察者：检测到路由变化 ${routeInfo.path}`)
    observerCount.value++
  })
  
  addLog('自定义观察者已添加')
  ElMessage.success('自定义观察者已添加')
}

const removeCustomObserver = () => {
  if (!customObserver.value) {
    ElMessage.warning('没有自定义观察者可移除')
    return
  }

  removeObserver(customObserver.value)
  customObserver.value = null
  
  addLog('自定义观察者已移除')
  ElMessage.success('自定义观察者已移除')
}

const triggerManualUpdate = () => {
  const testRouteInfo = {
    path: '/test-manual',
    name: 'test-manual',
    fullPath: '/test-manual?manual=true',
    timestamp: Date.now(),
    from: currentRoute.value
  }
  
  triggerUpdate(testRouteInfo)
  addLog('手动触发了路由更新事件')
  ElMessage.success('手动更新已触发')
}

onMounted(() => {
  // 设置默认观察者
  setupDefaultObservers()
  setupPerformanceMonitoring()
  
  // 初始化观察者计数
  observerCount.value = 5 // 默认观察者数量
  
  addLog('路由观察者演示页面已加载')
})
</script>

<style scoped>
.route-observer-demo {
  padding: 20px;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.demo-content {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.demo-section {
  padding: 20px 0;
}

.demo-section h3 {
  color: #409EFF;
  margin-bottom: 16px;
}

.demo-section ul {
  margin: 16px 0;
  padding-left: 20px;
}

.demo-section li {
  margin: 8px 0;
  color: #606266;
}

.observer-log {
  margin-top: 20px;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 8px;
  max-height: 300px;
  overflow-y: auto;
}

.observer-log h4 {
  margin-bottom: 16px;
  color: #303133;
}

.status-panel {
  padding: 16px 0;
}

.status-panel > div {
  margin-bottom: 20px;
}

.breadcrumb-display h4,
.performance-display h4,
.recent-routes h4 {
  margin-bottom: 12px;
  color: #409EFF;
  font-size: 14px;
}

.monitor-panel {
  margin-top: 30px;
}

.el-alert {
  margin-bottom: 16px;
}

.el-statistic {
  text-align: center;
}
</style>